package com.imy.lua.helper.color;

import android.graphics.Bitmap;

import android.graphics.Color;
import android.graphics.Point;


import com.imy.common.util.ColorUtils;

public class ImageColorHelper {





    private static boolean isMath(int ori, int target, float dim) {
        int abs = Math.abs(target - ori);
        if (abs == 0) {
            return true;
        }
        float p = (abs * 1.0f) / ori * 1.0f;
        float v = 1.0f - p;
        return v >= dim;
    }

    public static Point findColor(Bitmap bitmap, String color, int startX, int startY,
                                  int width, int height, float dim) {
        //检测函数
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();
        if (startX > bitmapWidth) {
            return null;
        }
        if (startY > bitmapHeight) {
            return null;
        }
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, startX, startY, width, height);
        Point color1 = findColor(newBitmap, color, dim);
        if (color1!=null){
            color1.x = color1.x + startX;
            color1.y = color1.y + startY;
        }
        return color1;
    }

    public static Point findColor(Bitmap bitmap, String color, float dim) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int startY = 0;
        for (int i = 0; i < height; i++) {
            Point point = getXColor(bitmap, width, startY, color, dim);
            if (point != null) {
                return point;
            }
            startY++;
        }
        return null;
    }


    public  static Point isColorMath(Bitmap bitmap, int x, int y, String color, float dim) {
        int pixel = bitmap.getPixel(x, y);
        int[] readColor = ColorUtils.parserRGB(pixel);
        int[] mathColor = ColorUtils.parserRGB(Color.parseColor(color));
        boolean red = isMath(mathColor[0], readColor[0], dim);
        boolean green = isMath(mathColor[1], readColor[1], dim);
        boolean blue = isMath(mathColor[2], readColor[2], dim);
        if (red && green && blue) {
            return new Point(x, y);
        }
        return null;
    }

    private static Point getXColor(Bitmap bitmap, int width, int startY, String color, float dim) {
        for (int i = 0; i < width; i++) {
            Point colorMath = isColorMath(bitmap, i, startY, color, dim);
            if (colorMath != null) {
                return colorMath;
            }
        }
        return null;
    }

    public static int getColor(Bitmap bitmap,int x, int y) {
        return bitmap.getPixel(x,y);
    }
}
